﻿package com.badibadi.activity;

import java.net.URLDecoder;
import java.util.List;
import java.util.Timer;

import com.badibadi.infos.Chat_Message_Model;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.DisplayUtil;
import com.badibadi.mytools.FileUtils;
import com.badibadi.mytools.JSONUtils;
import com.badibadi.mytools.Utils;
import com.badibadi.socket.Send_Geshi_Tool;
import com.badibadi.socket.SocketResultModel;
import com.badibadi.uniclubber.R;
import com.libjph.util.StringUtil;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 定义一些保存用户数据的变量  以及第三方登陆的一些准备
 * 
 * @author dust
 */
public class BaseActivity extends CommonActivity {// onRe

	/**
	 * 美图秀秀包名
	 */
	public String MEITUXIUXIU_PAGENAME = "com.mt.mtxx.mtxx";
	public String BADIBADI_PAGENAME = "com.badibadi.uniclubber";
	/** 美图秀秀的下载网址 **/
	public String MEITUXIUXIU_Uri = "http://xiuxiu.meitu.com/android/";
	public String BADIBADI_Uri = "http://www.uniclubber.com/";
	/**
	 * 俱乐部的数据存放路径
	 */
	public String SavePath = "/mnt/sdcard/com.badibadi.uniclubber/files";
	/**
	 * 上传照片存放路径
	 */
	public String UpPicSavePath = "/mnt/sdcard/com.badibadi.uniclubber/cropPic";
	/**
	 * 上传图片第二部传递路径的key
	 */
	public final String UpPictures1DataKey0 = "UpPictures1DataKey0";

	/**
	 * 上传图片1的message
	 */
	public final int UPSETMESSAGE = 0x01;

	public final int ProgressBarDialogkey = 1;

	public final int SCREENW = 0;
	public final int SCREENH = 1;

	public static float ScreenW, ScreenH;// 保存屏幕宽高，方便频繁调用；

	// 获取国家 用法，先要
	private String Guojia = "";
	// 设置省需要用到的
	private String Sheng = "";
	// 设置市需要用到的
	private String Shi = "";
	// 设置性别需要用到的
	private String Sex = "nan";
	private Spinner getSexViewspinner;

	private OnMyDialogeClistener onMyDialogeClistener;

	/**
	 * 俱乐部中张贴相关链接
	 */
	public static String HTTP_WEIBO = "http://www.weibo.com/";
	public static String HTTP_TWITTER = "http://www.twitter.com/";
	public static String HTTP_FACEBOOK = "http://www.facebook.com/";
	public static String HTTP_QQ = "";
	public static String HTTP_WEIXIN = "";
	public static String HTTP_LINKEDIN = "http://www.linkedin.com/";
	public Timer timer;
	private SocketResultModel resultModel;// socket返回数据实体类
	private Chat_Message_Model message_Model;

	private Message message;
	private Bundle bundle;
	// public int new_message_num = 0;

	// 接收
	public Handler mhandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			try {
				//    
				if (msg.obj != null) {
					String s = msg.obj.toString().trim();//
					if (s.trim().length() > 0) {
						s = Utils.unicodeToString(s);// 将unicode编码格式转换为中文
						s = URLDecoder.decode(s, "GB2312");// 转换符号转换格式
						if (s.equals("心跳...")) {
							//    
							Send_Geshi_Tool.xintiao = "判断成功";
						}

						String s1 = JieXi_Data_Login(s);
						if (s1.equals("Login")) {// 登陆服务器成功
							// Toast.makeText(getApplicationContext(),
							// "登陆聊天服务器成功", 0).show();
							// Time_XinTiao();
						} else if (s1.equals("LoginErr")) {// 登陆服务器失败
							Toast.makeText(
									getApplicationContext(),
									getResources()
											.getString(R.string.wx_txt_76), 0)
									.show();
						} else if (s1.equals("Talk")) {// 返回聊天信息
							if (resultModel.getId().equals(
									Utils.getUid(BaseActivity.this))) {
								message_Model = new Chat_Message_Model();
								message_Model.setMe_or_you("1");
								message_Model.setChat_message(resultModel
										.getMsg());
								message_Model.setChat_img("null");
								message_Model.setChat_name(resultModel
										.getName());
								message_Model.setChat_time(Utils
										.Get_System_Time("HH:mm"));
								message = new Message();
//								LogUtils.i(message_Model.toString());
								bundle = new Bundle();
								message.what = 2;
								bundle.putSerializable("me", message_Model);
								message.setData(bundle);
								Constants.Chat_handler.sendMessage(message);
							} else {// 别人发送的消息
								if (Constants.temp_socket_id != null
										&& resultModel.getId().equals(
												Constants.temp_socket_id)) {
									// 正在聊天的好友消息处理
									String ids = Utils
											.getBlack_list_id(BaseActivity.this);
									if (!StringUtil.isNullOrEmpty(ids)) {
										if (Utils.panduan_is_cunzai(ids, ",")) {// 黑名单里有多个人的话，就循环取出来比较发消息者是不是黑名单的人
											String ds[] = ids.split(",");
											boolean is_send = true;
											for (int i = 0; i < ds.length; i++) {
												if (resultModel.getId().equals(
														ds[i])) {
													is_send = false;
													break;
												} else {
													is_send = true;
												}
											}
											if (is_send) {
												message_Model = new Chat_Message_Model();
												message_Model.setMe_or_you("2");
												message_Model
														.setChat_message(resultModel
																.getMsg());
												message_Model
														.setChat_img("null");
												message_Model
														.setChat_name(resultModel
																.getName());
												message_Model
														.setChat_time(resultModel
																.getTime());
												message = new Message();
												bundle = new Bundle();
												message.what = 3;
												bundle.putSerializable("you",
														message_Model);
												message.setData(bundle);
												Constants.Chat_handler
														.sendMessage(message);
											}
										} else {
											if (!resultModel.getId()
													.equals(ids)) {// 不是黑名单的人
												message_Model = new Chat_Message_Model();
												message_Model.setMe_or_you("2");
												message_Model
														.setChat_message(resultModel
																.getMsg());
												message_Model
														.setChat_img("null");
												message_Model
														.setChat_name(resultModel
																.getName());
												message_Model
														.setChat_time(resultModel
																.getTime());
												message = new Message();
												bundle = new Bundle();
												message.what = 3;
												bundle.putSerializable("you",
														message_Model);
												message.setData(bundle);
												Constants.Chat_handler
														.sendMessage(message);
											}
										}
									} else {// 黑名单里没有人
										message_Model = new Chat_Message_Model();
										message_Model.setMe_or_you("2");
										message_Model
												.setChat_message(resultModel
														.getMsg());
										message_Model.setChat_img("null");
										message_Model.setChat_name(resultModel
												.getName());
										message_Model.setChat_time(resultModel
												.getTime());
										message = new Message();
										bundle = new Bundle();
										message.what = 3;
										bundle.putSerializable("you",
												message_Model);
										message.setData(bundle);
										Constants.Chat_handler
												.sendMessage(message);
									}

								} else {
									String ids = Utils
											.getBlack_list_id(BaseActivity.this);
									if (!StringUtil.isNullOrEmpty(ids)) {
										if (Utils.panduan_is_cunzai(ids, ",")) {// 黑名单里有多个人的话，就循环取出来比较发消息者是不是黑名单的人
											String ds[] = ids.split(",");
											boolean is_send = true;
//											   
											for (int i = 0; i < ds.length; i++) {
												if (resultModel.getId().equals(
														ds[i])) {
													is_send = false;
													break;
												} else {
													is_send = true;
												}
											}
											if (is_send) {
												++Send_Geshi_Tool.new_message_num;
//												   
//														+ resultModel.getTime());
												message_Model = new Chat_Message_Model();
												message_Model
														.setNew_mess_uid(resultModel
																.getId());
												message_Model.setMe_or_you("0");
												message_Model
														.setChat_message(resultModel
																.getMsg());
												message_Model
														.setChat_img("null");
												message_Model
														.setChat_name(resultModel
																.getName());
												message_Model
														.setChat_time(resultModel
																.getTime());
												Send_Geshi_Tool.chat_Message_Models
														.add(message_Model);
												Constants.New_Mes_handler
														.sendEmptyMessage(6);
												if (Send_Geshi_Tool.public_new_mes_handler != null) {
													Send_Geshi_Tool.public_new_mes_handler
															.sendEmptyMessage(6);
												}
											}
										} else {
//											   
											if (!resultModel.getId()
													.equals(ids)) {// 不是黑名单的人
												++Send_Geshi_Tool.new_message_num;
//												   
//														+ resultModel.getTime());
												message_Model = new Chat_Message_Model();
												message_Model
														.setNew_mess_uid(resultModel
																.getId());
												message_Model.setMe_or_you("0");
												message_Model
														.setChat_message(resultModel
																.getMsg());
												message_Model
														.setChat_img("null");
												message_Model
														.setChat_name(resultModel
																.getName());
												message_Model
														.setChat_time(resultModel
																.getTime());
												Send_Geshi_Tool.chat_Message_Models
														.add(message_Model);
												Constants.New_Mes_handler
														.sendEmptyMessage(6);
												if (Send_Geshi_Tool.public_new_mes_handler != null) {
													Send_Geshi_Tool.public_new_mes_handler
															.sendEmptyMessage(6);
												}
											}
										}
									} else {// 黑名单里没有人
//										   
										++Send_Geshi_Tool.new_message_num;
//										   
//												"时间是:" + resultModel.getTime());
										message_Model = new Chat_Message_Model();
										message_Model
												.setNew_mess_uid(resultModel
														.getId());
										message_Model.setMe_or_you("0");
										message_Model
												.setChat_message(resultModel
														.getMsg());
										message_Model.setChat_img("null");
										message_Model.setChat_name(resultModel
												.getName());
										message_Model.setChat_time(resultModel
												.getTime());
										Send_Geshi_Tool.chat_Message_Models
												.add(message_Model);
										Constants.New_Mes_handler
												.sendEmptyMessage(6);
										if (Send_Geshi_Tool.public_new_mes_handler != null) {
											Send_Geshi_Tool.public_new_mes_handler
													.sendEmptyMessage(6);
										}
									}
								}
							}
						}
					} else {
						//    
					}
				}
			} catch (Exception ee) {
//				   ("加载过程出现异常");
			}
		}
	};

	// 发送
	public Handler mhandlerSend = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			try {
msg.obj.toString();
				if (msg.what == 1) {
					// Toast.makeText(getApplicationContext(),
					// "\n ME: " + s + "      发送成功", 1).show();
//					   ("\n ME: " + s + "      发送成功");
				} else {
//					Toast.makeText(getApplicationContext(),
//							getResources().getString(R.string.wx_send_false), 1)
//							.show();
					//    ("\n ME: " + s + "     发送失败");
				}
			} catch (Exception ee) {
//				   ("加载过程出现异常");
			}
		}
	};

	// 错误
	public Handler error_handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
//				Toast.makeText(getApplicationContext(),
//						msg.getData().getString("result"), 0).show();
				break;
			case 2:
				Send_Geshi_Tool.startSocket(mhandler, mhandlerSend,
						error_handler, BaseActivity.this);
				break;
			case 3:
				// timer.cancel();
				break;

			default:
				break;
			}
		}
	};


	public String JieXi_Data_Login(String s) throws Exception {

		resultModel = new SocketResultModel();
		resultModel = JSONUtils.getEntityByJsonString(s,
				SocketResultModel.class);
		return resultModel.getSIGN();
	}

	/**
	 * @param RETURN_SCREEN
	 *            RETURN_SCREENW为返回宽 RETURN_ SCREENH 为返回高
	 * @return 返回-1为空
	 */
	public float getScreenSize(int RETURN_SCREEN) {
		DisplayMetrics metrics = new DisplayMetrics();// 获取屏幕宽高
		this.getWindowManager().getDefaultDisplay().getMetrics(metrics);// 1。获取窗口管理器，2默认的屏幕，3获取屏幕的大小（赋值给metrcs）

		ScreenW = metrics.widthPixels;
		ScreenH = metrics.heightPixels;
		if (RETURN_SCREEN == SCREENW)
			return ScreenW;
		else if (RETURN_SCREEN == SCREENH)
			return ScreenH;
		return -1;
	}

	/**
	 * 设置全屏 去标题
	 */
	public void setFullScreen() {
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);// 去标题
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);// 去掉信息栏；

	}

	// 去标题
	public void goToTheTitle() {
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);// 去标题
	}


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		new com.badibadi.mytools.Dialog().initLanguage(BaseActivity.this);
	}
	@Override
	protected void onResume() {
		/**
		 * 设置为竖立屏
		 */
		if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		}
		super.onResume();

	}// 强制横屏；不能切换

	@Override
	protected void onPause() {
		super.onPause();

	}

	public class ViewFragmentHolder {

		public FragmentManager manager;
		public FragmentTransaction transaction;

		public ViewFragmentHolder() {
			manager = getSupportFragmentManager();
			transaction = manager.beginTransaction();
		}

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// stopSocket();
	}

	public void ShowToast(Context context, String Infos) {
		Toast.makeText(context, "" + Infos, 0).show();
	}


	/**
	 * http://www.eoeandroid.com/thread-241898-1-1.html 获取view的宽高
	 * 
	 * @param v
	 *            view
	 * @param isReturnW
	 *            是否返回宽，否则返回高
	 * @return
	 */
	public int getKH(View v, boolean isReturnW) {
		int w = View.MeasureSpec.makeMeasureSpec(0,
				View.MeasureSpec.UNSPECIFIED);
		int h = View.MeasureSpec.makeMeasureSpec(0,
				View.MeasureSpec.UNSPECIFIED);
		v.measure(w, h);
		if (isReturnW == true) {
			int width = v.getMeasuredWidth();
			return width;
		} else {
			int height = v.getMeasuredHeight();
			return height;
		}
	}

	public void PopSetting(PopupWindow pop) {
		pop.setBackgroundDrawable(new BitmapDrawable());
		pop.setFocusable(true);
		pop.setTouchable(true);
		pop.setOutsideTouchable(true);

	}

	public void EnterWebView(String sourse) {
		if (sourse.indexOf("http://") == -1) {
			sourse = "http://" + sourse;
		}
		Uri uri = Uri.parse(sourse);
		Intent intent = new Intent(Intent.ACTION_VIEW, uri);
		if (intent != null) {
			startActivity(intent);
			intent = null;
		}

	}


	/** 设置性别的对话框 */
	public void setSexDialog(Context ct) {
		new AlertDialog.Builder(ct)
				.setTitle(getResources().getString(R.string.PleaseChoseSex_))
				.setView(getSexView(ct))
				.setNegativeButton(getResources().getString(R.string.ok),
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								Sex = getSexViewspinner.getSelectedItem()
										.toString();
								if (onMyDialogeClistener != null) {
									onMyDialogeClistener.Ok();
									onMyDialogeClistener = null;
								}
							}
						})
				.setPositiveButton(getResources().getString(R.string.cancel),
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								if (onMyDialogeClistener != null) {
									onMyDialogeClistener.Cancle();
									onMyDialogeClistener = null;
								}
							}
						}).show();

	}

	private View getSexView(Context context) {
		int dip5_px = DisplayUtil.dip2px(context, 5);
		LinearLayout ll = new LinearLayout(context);
		ll.setOrientation(LinearLayout.VERTICAL);
		LinearLayout l1 = new LinearLayout(context);
		l1.setOrientation(LinearLayout.HORIZONTAL);
		getSexViewspinner = new Spinner(context);
		getSexViewspinner.setLayoutParams(new LinearLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, DisplayUtil.dip2px(context, 50), 1));
		getSexViewspinner.setBackgroundResource(R.drawable.shape_layout_bg);
		String[] arr1 = getResources().getStringArray(R.array.sex);
		TextView tv1 = new TextView(context);
		tv1.setText(R.string.sex_);
		tv1.setPadding(dip5_px, 0, 0, 0);
		ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(context,
				android.R.layout.simple_list_item_1, arr1);
		getSexViewspinner.setAdapter(adapter1);
		Sex = getSexViewspinner.getSelectedItem().toString();
		l1.addView(tv1);
		l1.addView(getSexViewspinner);
		l1.setPadding(0, dip5_px, dip5_px, dip5_px);
		return l1;
	}


	/**
	 * 调用第三方软件
	 * 
	 * @param PakeName
	 *            包名
	 * @param uri
	 *            假设没有安装这个软件就打开这个网站
	 */
	public void OpenTheThirdPartySoftWare(String PakeName, final String mUri) {
		// Call the third party software
		PackageManager packageManager = this.getPackageManager();
		List<PackageInfo> packageInfoList = packageManager
				.getInstalledPackages(0);
		boolean isPresence = false;// 是否安装需要打开的软件
		// 下面的就是正式开始调用
		for (int i = 0; i < packageInfoList.size(); i++) {
			PackageInfo pak = (PackageInfo) packageInfoList.get(i);
			if (pak.applicationInfo.packageName.equals(PakeName)) {
				isPresence = true;
				break;
			}
		}
		if (isPresence) {
			Intent intent = new Intent();
			intent = packageManager.getLaunchIntentForPackage(PakeName);
			startActivity(intent);
		} else {
			new AlertDialog.Builder(this)
					.setTitle(getResources().getString(R.string.wx_txt_77))
					.setMessage(getResources().getString(R.string.wx_txt_78))
					.setPositiveButton(
							getResources().getString(R.string.OK),
							new android.content.DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.dismiss();
									EnterWebView(mUri);
								}
							})
					.setNegativeButton(
							getResources().getString(R.string.Cancle),
							new android.content.DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.dismiss();
								}
							}).show();

		}
	}

	public void getFileSavePath(Context context, String filename) {
		SavePath = FileUtils.getFileAbsolutePath(context, filename);
	}

	public void setOnMyDialogeClistener(OnMyDialogeClistener listener) {
		onMyDialogeClistener = listener;
	}

	public interface OnMyDialogeClistener {
		void Ok();

		void Cancle();
	}

	public String getSex() {
		return Sex;
	}

	public void setSex(String sex) {
		Sex = sex;
	}

	public String getGuojia() {
		return Guojia;
	}

	public void setGuojia(String guojia) {
		Guojia = guojia;
	}

	public String getSheng() {
		return Sheng;
	}

	public void setSheng(String sheng) {
		Sheng = sheng;
	}

	public String getShi() {
		return Shi;
	}

	public void setShi(String shi) {
		Shi = shi;
	}

}
